import { routerRedux } from 'dva/router';
import { stringify } from 'querystring';
import { accountLogin, getFakeCaptcha, logout } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { reloadAuthorized } from '@/utils/Authorized';
import { getPageQuery } from '@/utils/utils';
import { Role } from '@/constants/power';
import UserReducer from '@/dva/user';

const { State, Reducers } = UserReducer;

const Model = {
  namespace: 'login',
  state: {
    status: State,
  },
  reducers: {
    [Reducers.setState](state, { data = {} } = {}) {
      // console.log('来了吗');
      return {
        ...state,
        ...data,
      };
    },
  },
  effects: {
    // 登录方法
    *login({ payload }, { call, put }) {
      try {
        const response = yield call(accountLogin, payload);
        console.log('看看这个数据', response);
        // return
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        }); // Login successfully
        if (response.status === 'ok') {
          yield put({
            type: `${UserReducer.Namespace}/${UserReducer.Reducers.saveCurrentUser}`,
            payload: response.response,
          });
          localStorage.setItem('user', JSON.stringify(response.response))
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          let { redirect } = params;
          const users = JSON.parse(localStorage.getItem('userroute'))
          if (redirect) {
            const redirectUrlParams = new URL(redirect);

            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);

              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            }
            if (users) {
              if (users.user_id === response.response.user_id) {
                window.location.href = redirect;
              } else {
                yield put(routerRedux.replace('/'));
              }
            } else {
              yield put(routerRedux.replace('/'));
            }
            // return
            localStorage.setItem('userroute', JSON.stringify(response.response))
            return;
          }
          yield put(routerRedux.replace('/'));
          localStorage.setItem('userroute', JSON.stringify(response.response))
        }
      } catch (e) {
        console.error(e);
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: 'error',
          },
        });
      }
    },
    // 获取验证码
    * getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
    // 登出方法
    * logout({ http = false }, { put, call }) {
      const { redirect } = getPageQuery(); // redirect
      if (window.location.pathname !== '/user/login' && !redirect) {
        localStorage.removeItem('user');
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          }),
        );
      }
      if (http) {
        yield call(logout);
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      if (payload.response) {
        const power = Role[payload.response.roleId] || [];
        console.log('这个是等苦的时候，', power)
        setAuthority(power);
        reloadAuthorized();
      }
      return {
        ...state,
        status: payload.status,
      };
    },
  },
};
export default Model;
